package com.wukong.alive.service;

import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ProcessUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.wukong.alive.CacheKey;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class LocalService extends Service {
    private final static int NOTIFICATION_ID = 1003;
    private static final String TAG = "LocalService";
    private ServiceConnection serviceConnection;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //此处可以写上一些业务逻辑
        Log.i(TAG, "LocalService onCreate: 本地服务启动了！");
        checkThread.start();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            showFloatingWindow();
        }
        try {
            Notification notification = new Notification();
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startForeground(NOTIFICATION_ID, notification);
            } else {
                startForeground(NOTIFICATION_ID, notification);
                // start InnerService
                startService(new Intent(this, InnerService.class));
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        serviceConnection = new LocalServiceConnection();
        startService(new Intent(this, RemoteService.class));
        bindService(new Intent(this, RemoteService.class), serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }


    class LocalServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "bind RemoteService");
            //服务连接后回调
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "remote service died，make it alive");
            //连接中断后回调
            startService(new Intent(LocalService.this, RemoteService.class));
            bindService(new Intent(LocalService.this, RemoteService.class), serviceConnection,
                    BIND_AUTO_CREATE);
        }
    }


    public static class InnerService extends Service {

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            try {
                startForeground(NOTIFICATION_ID, new Notification());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            stopSelf();
        }

        @Override
        public void onDestroy() {
            stopForeground(true);
            super.onDestroy();
        }
    }

    Thread checkThread = new Thread() {
        @Override
        public void run() {
            super.run();
            while (true) {
                try {
                    Thread.sleep(20000);
                    Log.i(TAG, "检测应用监控");

                    String isOpenApp = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_isOpenApp, "false");
                    if (!isOpenApp.equals("true")) {
                        Log.i(TAG, "应用监控未开启");
                        continue;
                    }

                    String isOpenReboot = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_isOpenReboot, "false");
                    if (isOpenReboot.equals("true")) {
                        Log.i(TAG, "定时重启服务已开启");
                        String time = TimeUtils.getString(new Date(), TimeUtils.getSafeDateFormat("HH:mm"), 0, TimeConstants.SEC);

                        List<String> rebootTimer = getRebootList();
                        for (String t : rebootTimer) {
                            Log.i(TAG,"时间比较："+t+"|"+time);
                            if (time.equals(t)) {
                                String cmd = " reboot" ;
                                Log.i(TAG, "执行命令：" + cmd);
                                ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmd, true);
                                Log.i(TAG, "执行结果：" + commandResult.errorMsg + " | " + commandResult.successMsg);
                                Thread.sleep(41000);
                            }
                        }
                    }


                    //获取监控的应用
                    String appPackage = CacheDiskUtils.getInstance().getString("appPackage");

                    String isOpenTimer = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_isOpenTimer, "false");
                    if (isOpenTimer.equals("true")) {
                        Log.i(TAG, "定时服务已开启");
                        String time = TimeUtils.getString(new Date(), TimeUtils.getSafeDateFormat("HH:mm"), 0, TimeConstants.SEC);

                        List<String> timers = getTimerList();
                        for (String t : timers) {
                            Log.i(TAG,"时间比较："+t+"|"+time);
                            if (time.equals(t)) {
                                if (!StringUtils.isEmpty(appPackage)) {
                                    ProcessUtils.killBackgroundProcesses(appPackage);
                                    String cmd = " am force-stop " + appPackage;
                                    Log.i(TAG, "执行命令：" + cmd);
                                    ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmd, true);
                                    Log.i(TAG, "执行结果：" + commandResult.errorMsg + " | " + commandResult.successMsg);
                                    Log.i(TAG, "关闭应用 pid");
                                    //1.为了解决定时问题 2解决关闭后立即重启问题
                                    Thread.sleep(41000);
                                }
                            }
                        }
                    }


                    if (!StringUtils.isEmpty(appPackage)) {
                        boolean isrun = AppUtils.isAppRunning(appPackage);
                        if (!isrun) {
                            Log.i(TAG, "检测到应用未启动启动应用");
                            AppUtils.launchApp(appPackage);
                        }
                        String foreground= ProcessUtils.getForegroundProcessName();
                        Log.i(TAG, "前端运行的应用:"+foreground);
                        boolean isForeground = AppUtils.isAppForeground(appPackage);
                        if (!isForeground) {
                            Log.i(TAG, "检测到应用未前端运行强制切到前端运行");
                            ProcessUtils.killBackgroundProcesses(appPackage);
                            AppUtils.launchApp(appPackage);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private List<String> getTimerList() {
        String timer1 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_timer1);
        String timer2 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_timer2);
        String timer3 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_timer3);
        String timer4 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_timer4);
        String timer5 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_timer5);
        List<String> timers = new ArrayList<>();
        if (!StringUtils.isEmpty(timer1)) {
            timers.add(timer1);
        }
        if (!StringUtils.isEmpty(timer2)) {
            timers.add(timer2);
        }
        if (!StringUtils.isEmpty(timer3)) {
            timers.add(timer3);
        }
        if (!StringUtils.isEmpty(timer4)) {
            timers.add(timer4);
        }
        if (!StringUtils.isEmpty(timer5)) {
            timers.add(timer5);
        }
        return timers;
    }


    private List<String> getRebootList() {
        String reboot1 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_reboot1);
        String reboot2 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_reboot2);
        String reboot3 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_reboot3);
        String reboot4 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_reboot4);
        String reboot5 = CacheDiskUtils.getInstance().getString(CacheKey.cacheKey_reboot5);
        List<String> reboots = new ArrayList<>();
        if (!StringUtils.isEmpty(reboot1)) {
            reboots.add(reboot1);
        }
        if (!StringUtils.isEmpty(reboot2)) {
            reboots.add(reboot2);
        }
        if (!StringUtils.isEmpty(reboot3)) {
            reboots.add(reboot3);
        }
        if (!StringUtils.isEmpty(reboot4)) {
            reboots.add(reboot4);
        }
        if (!StringUtils.isEmpty(reboot5)) {
            reboots.add(reboot5);
        }
        return reboots;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void showFloatingWindow() {
        if (Settings.canDrawOverlays(this)) {
            // 获取WindowManager服务
            WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

            // 新建悬浮窗控件
            TextView button = new TextView(getApplicationContext());

            button.setBackgroundColor(Color.TRANSPARENT);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(LocalService.this, "我还活着", Toast.LENGTH_SHORT).show();
                }
            });

            // 设置LayoutParam
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            layoutParams.format = PixelFormat.RGBA_8888;
            layoutParams.width = ConvertUtils.dp2px(10);
            layoutParams.height = ConvertUtils.dp2px(10);
            ;
            layoutParams.x = 1;
            layoutParams.y = 1;
            layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            // 将悬浮窗控件添加到WindowManager
            windowManager.addView(button, layoutParams);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
